package com.yidu.qianfeng.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yidu.qianfeng.common.bean.Vehicle.CarInfo;
import com.yidu.qianfeng.common.bean.company.EmpInfo;
import com.yidu.qianfeng.common.bean.company.Subst;
import com.yidu.qianfeng.common.bean.track.TrackWaybillCondition;
import com.yidu.qianfeng.common.bean.track.TrackWaybillWrap;
import com.yidu.qianfeng.common.bean.transport.Signfor;
import com.yidu.qianfeng.common.bean.transport.TrackWaybill;
import com.yidu.qianfeng.common.bean.transport.TransportProtocol;
import com.yidu.qianfeng.common.bean.transport.TruckLoading;
import com.yidu.qianfeng.common.bean.waybill.Waybill;
import com.yidu.qianfeng.common.util.JsonMsgUtil;
import com.yidu.qianfeng.common.util.LayuiJsonWrap;
import com.yidu.qianfeng.common.util.PrimaryKeyUtil;
import com.yidu.qianfeng.mapper.SubstationMapper;
import com.yidu.qianfeng.mapper.TrackWaybillMapper;
import com.yidu.qianfeng.mapper.WaybillMapper;
import com.yidu.qianfeng.service.TrackWaybillService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Author: TangSheng
 * @Description: 运单跟踪业务实现
 * @Date Created in 14:27 2021/3/29
 * @since 1.0
 */
@Service("trackWaybillServiceImpl")
public class TrackWaybillServiceImpl implements TrackWaybillService {

    @Resource(name = "trackWaybillMapper")
    private TrackWaybillMapper trackWaybillMapper;

    @Resource(name = "waybillMapper")
    private WaybillMapper waybillMapper;

    @Resource(name = "substationMapper")
    private SubstationMapper substationMapper;

    @Override
    public String generateTrackAccept(Waybill waybill, EmpInfo loginEmpInfo) {
        //跟踪记录
        TrackWaybill trackWaybill = null;
        try {
            trackWaybill = generateTrackWaybillEntity(waybill,loginEmpInfo);
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
        //跟踪类型
        trackWaybill.setTrackType(1);
        //1:发站库存，收件    新增运单后
        trackWaybill.setTrackStatus("【"+substationMapper.selectById(waybill.getWaybillStartingSubst()).getSubstName()+"】"+"已受理运单。");

        //新增跟踪记录
        trackWaybillMapper.insert(trackWaybill);

        return trackWaybill.getTrackId();
    }

    @Override
    public String generateTrackPreLoadCar(Waybill waybill, EmpInfo loginEmpInfo) {
        //跟踪记录
        TrackWaybill trackWaybill = null;
        try {
            trackWaybill = generateTrackWaybillEntity(waybill,loginEmpInfo);
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
        //跟踪类型
        trackWaybill.setTrackType(2);
        //2:准备装车  准备装车时
        trackWaybill.setTrackStatus("运单号："+waybill.getWaybillConsignNum()+"准备装车");
        //新增跟踪记录
        trackWaybillMapper.insert(trackWaybill);

        return trackWaybill.getTrackId();
    }

    @Override
    @Transactional
    public List<String> generateTrackLoadCar(TruckLoading truckLoading, EmpInfo loginEmpInfo) {

        //跟踪记录列表
        List<String> trackIds = new ArrayList<>();

        String[] waybillConsignNums = truckLoading.getCarloadlist().trim().split(",");

        List<Waybill> waybills = waybillMapper.selectBatchIds(Arrays.asList(waybillConsignNums));


        for (Waybill waybill : waybills) {
            //跟踪记录
            TrackWaybill trackWaybill = null;
            try {
                trackWaybill = generateTrackWaybillEntity(waybill,loginEmpInfo);
            } catch (Exception e) {
                System.err.println(e.getMessage());
            }
            //跟踪类型
            trackWaybill.setTrackType(3);
            //3:已装车，装车      装车后
            trackWaybill.setTrackStatus("运单号："+waybill.getWaybillConsignNum()+"，已完成装车，准备发运");

            //添加到跟踪记录列表中
            trackIds.add(trackWaybill.getTrackId());

            //新增跟踪记录
            trackWaybillMapper.insert(trackWaybill);
        }

        return trackIds;
    }

    @Override
    @Transactional
    public List<String> generateTrackTrans(TransportProtocol transportProtocol, EmpInfo loginEmpInfo) {

        //跟踪记录列表
        List<String> trackIds = new ArrayList<>();

        String[] waybillConsignNums = transportProtocol.getTransCarloadList().trim().split(",");

        List<Waybill> waybills = waybillMapper.selectBatchIds(Arrays.asList(waybillConsignNums));


        for (Waybill waybill : waybills) {
            //跟踪记录
            TrackWaybill trackWaybill = null;
            try {
                trackWaybill = generateTrackWaybillEntity(waybill,loginEmpInfo);
            } catch (Exception e) {
                System.err.println(e.getMessage());
            }

            //跟踪类型
            trackWaybill.setTrackType(4);

            //4:运输途中，运输    新增运输协议后
            trackWaybill.setTrackStatus(transportProtocol.getTransStarting()+"已发车，运输车号："+transportProtocol.getTransCarNumber());

            //添加到跟踪记录列表中
            trackIds.add(trackWaybill.getTrackId());

            //新增跟踪记录
            trackWaybillMapper.insert(trackWaybill);
        }
        return trackIds;
    }

    @Override
    public String generateTrackShunt(Waybill waybill,Subst subst,EmpInfo loginEmpInfo) {
        //跟踪记录
        TrackWaybill trackWaybill = null;
        try {
            trackWaybill = generateTrackWaybillEntity(waybill,loginEmpInfo);
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
        //跟踪类型
        trackWaybill.setTrackType(5);
        //5:到站库存，转运    卸货入库后
        trackWaybill.setTrackStatus("货物己到达"+subst.getSubstName());

        //新增跟踪记录
        trackWaybillMapper.insert(trackWaybill);

        return trackWaybill.getTrackId();
    }

    @Override
    public String generateTrackDelivery(Waybill waybill, CarInfo carInfo, EmpInfo loginEmpInfo) {
        //跟踪记录
        TrackWaybill trackWaybill = null;
        try {
            trackWaybill = generateTrackWaybillEntity(waybill,loginEmpInfo);
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
        //跟踪类型
        trackWaybill.setTrackType(6);
        //6:派送出库 ，货物己由刘先生派送出库，联系电话:18569392207
        trackWaybill.setTrackStatus("货物已由"+carInfo.getCarDriver()+"派送出库，联系电话："+carInfo.getCarDriverPhone());

        //新增跟踪记录
        trackWaybillMapper.insert(trackWaybill);

        return trackWaybill.getTrackId();
    }

    @Override
    public String generateTrackSignFor(Waybill waybill, String signForMessage,EmpInfo loginEmpInfo) {
        //跟踪记录
        TrackWaybill trackWaybill = null;
        try {
            trackWaybill = generateTrackWaybillEntity(waybill,loginEmpInfo);
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
        //跟踪类型
        trackWaybill.setTrackType(7);
        //7：运单签收
        if (signForMessage != "" && signForMessage != null){
            trackWaybill.setTrackStatus(signForMessage);
        } else {
            trackWaybill.setTrackStatus("运单已签收");
        }

        //新增跟踪记录
        trackWaybillMapper.insert(trackWaybill);

        return trackWaybill.getTrackId();
    }



    @Override
    public Integer cascadeDeleteTrack(Waybill waybill, Integer trackType) {
        QueryWrapper<TrackWaybill> wrapper = new QueryWrapper<>();
        wrapper.eq("track_consign_num", waybill.getWaybillConsignNum());
        wrapper.eq("track_type", trackType);
        Integer delete = trackWaybillMapper.delete(wrapper);

        return delete;
    }

    @Override
    @Transactional
    public Integer cascadeDeleteTrack(List<String> waybillConsignNums, Integer trackType) {

        QueryWrapper<TrackWaybill> wrapper = new QueryWrapper<>();
        wrapper.in("track_consign_num", waybillConsignNums);
        wrapper.eq("track_type", trackType);
        int delete = trackWaybillMapper.delete(wrapper);

        return delete;
    }

    /**
     *  根据运单生成跟踪记录实体
     * @param waybill 运单实体 ！必须带托运单号
     * @return 生成的实体，包含录入站点、主键、托运单号、跟踪日期
     */
    private TrackWaybill generateTrackWaybillEntity(Waybill waybill,EmpInfo empInfo) throws Exception {
        if (waybill.getWaybillConsignNum() == null || waybill.getWaybillConsignNum() == ""){
            throw new Exception("ERROR: 运单托运单号不能为空!---");
        }
        TrackWaybill trackWaybill = new TrackWaybill();

        //跟踪记录录入站点
        trackWaybill.setTrackRecordSubst(empInfo.getEmpSubstId());
        //生成跟踪主键
        trackWaybill.setTrackId(PrimaryKeyUtil.generateTrackKey(waybill.getWaybillConsignNum()));
        //跟踪表记录的托运单号
        trackWaybill.setTrackConsignNum(waybill.getWaybillConsignNum());
        //生成跟踪日期
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        trackWaybill.setTrackDate(formatter.format(new Date()));

        return trackWaybill;
    }

    @Override
    public String addTrack(TrackWaybill trackWaybill) {
        //生成并保存运单跟踪记录的主键
        String trackKey = PrimaryKeyUtil.generateTrackKey(trackWaybill.getTrackConsignNum());
        trackWaybill.setTrackId(trackKey);

        int insert = trackWaybillMapper.insert(trackWaybill);

        return JsonMsgUtil.createJsonMessage(insert, "新增跟踪记录成功", "新增跟踪记录失败");
    }

    @Override
    public LayuiJsonWrap queryTrackLimitLayui(Integer page, Integer limit) {
        int offset = (page-1)*limit;//计算偏移量
        List<TrackWaybillWrap> trackWaybillWraps = trackWaybillMapper.selectTrackLimit(offset, limit);

        return new LayuiJsonWrap(trackWaybillMapper.selectCount(null), trackWaybillWraps);
    }

    @Override
    public String deleteTrack(String trackId) {

        int delete = trackWaybillMapper.deleteById(trackId);

        return JsonMsgUtil.createJsonMessage(delete, "删除跟踪记录成功", "删除跟踪记录，请稍后再试。");
    }

    @Override
    public String updateTrackById(TrackWaybill track) {
        int update = trackWaybillMapper.updateById(track);

        return JsonMsgUtil.createJsonMessage(update, "修改记录成功", "修改记录失败,请稍后再试");

    }

    @Override
    public TrackWaybill queryOneTrackById(String trackId) {
        return trackWaybillMapper.selectById(trackId);
    }

    @Override
    public LayuiJsonWrap queryTrackByConditionLayui(TrackWaybillCondition trackWaybillCondition) {
        //计算并set偏移量
        trackWaybillCondition.setOffset((trackWaybillCondition.getPage()-1) * trackWaybillCondition.getCount());
        //根据条件分页查询
        List<TrackWaybillWrap> trackWaybillWraps = trackWaybillMapper.selectTrackByCondition(trackWaybillCondition);
        //包装成layui格式并返回
        return new LayuiJsonWrap(trackWaybillMapper.selectTrackCountByCondition(trackWaybillCondition), trackWaybillWraps);

    }

    @Override
    public LayuiJsonWrap queryTrackNoSign(int page,int limit) {
        //查询未签收的运单跟踪记录包装数据列表
        List<TrackWaybillWrap> trackWaybillWraps = trackWaybillMapper.selectNoSignTrack((page-1)*limit,limit);
        return new LayuiJsonWrap(trackWaybillMapper.selectNoSignTrackCount(), trackWaybillWraps);
    }

    /**
     * 查询已签收的运单信息
     * @param page 页面
     * @param limit 页目
     * @return
     */
    @Override
    public List<TrackWaybill> selectSignforPaing(int page,int limit) {

        return trackWaybillMapper.selectSignforPaing(page,limit);
    }

    /**
     * 查询已签收的运单信息
     * @return
     */
    @Override
    public int selectSignforCount() {

        return trackWaybillMapper.selectSignforCount();
    }

    /**
     * 根据托运单号查询数据
     * @param trackConsignNum 托运单号
     * @return 结果对象
     */
    @Override
    public List<TrackWaybill> bytrackConsignNumSelect(String trackConsignNum) {

        return trackWaybillMapper.bytrackConsignNumSelect(trackConsignNum);
    }

    /**
     * 查询派送中的托运单号
     * @return 对象集合
     */
    @Override
    public List<TrackWaybill> getTrackConsignNum() {

        return trackWaybillMapper.getTrackConsignNum();
    }

    /**
     * 根据托运单号查询到达站司机
     * @param trackConsignNum 托运单号
     * @return 结果集合对象
     */
    @Override
    public List<TrackWaybill> byTrackConsignNumQueryDriver(String trackConsignNum) {

        return trackWaybillMapper.byTrackConsignNumQueryDriver(trackConsignNum);
    }

    /**
     * 新增签收表
     * @param signfor 签收表表对象
     * @return 结果信息
     */
    @Override
    public String addSignfor(Signfor signfor) {
        int result = trackWaybillMapper.addSignfor(signfor);

        return JsonMsgUtil.createJsonMessage(result,"新增成功","新增失败");
    }

    /**
     * 修改运单跟踪表跟踪类型
     * @param trackId 主键id
     * @return 结果
     */
    @Override
    public int updatetrackType(String trackId,String trackStatus,String trackReceiptPhotoUrl) {

        return trackWaybillMapper.updatetrackType(trackId,trackStatus,trackReceiptPhotoUrl);
    }
}
